package 线程和TCP网络编程.TAKS2.失败品.Server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务器端
 *
 * @author 君未洋
 */
public class Server {

    public static List<Socket> list = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(8087);
        System.out.println("启动成功");
        /*ExecutorService executorService = Executors.newCachedThreadPool();*/
        //获取客户端对象
        while (true) {
            Socket socket = serverSocket.accept();
            list.add(socket);
            /*executorService.submit(new ServerRunnableImpl(socket));*/
            new Thread(new ServerRunnableImpl(socket));
        }

    }
}

class ServerRunnableImpl implements Runnable {

    public Socket socket;

    public ServerRunnableImpl(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //用字符缓冲流来缓冲输入对象
            while (true) {
                String str = br.readLine();
                for (Socket s : Server.list) {
                    PrintWriter pw = new PrintWriter(s.getOutputStream());
                    pw.print(str);
                    pw.flush();
                    pw.close();

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
